package com.example.demo.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.utils.Constant;
import com.example.demo.utils.Util;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/weather")
public class WeatherController {
	
	
	private static Logger logger = LoggerFactory.getLogger(WeatherController.class);
	
	@RequestMapping(value = "getTemperature")
	public ResponseEntity<JSONObject> getTemperatureByLocation(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			String location = request.getParameter("location");
			if (StringUtils.isNotBlank(location)) {
				Map<String, String> stationMap = (Map<String, String>)request.getSession().getAttribute("station");
				if (stationMap == null) {
					Util.getArea(request);
					stationMap = (Map<String, String>)request.getSession().getAttribute("station");
				} 
				String stationCode = stationMap.get(location);
				if (StringUtils.isNotBlank(stationCode)) {
					JSONObject stationJo = Util.interfaceUtil("http://www.weather.com.cn/data/sk/" + stationCode + ".html");
					jsonObject.put(Constant.RESULT, Constant.SUCCESS);
					jsonObject.put(Constant.DATA, stationJo);
				} else {
					jsonObject.put(Constant.RESULT, Constant.FAIL);
					jsonObject.put(Constant.ERR_MESSAGE, "当前地区不正确，请输入正确的地区");
					logger.error("当前地区不正确，请输入正确的地区");
				}
			} else {
				jsonObject.put(Constant.RESULT, Constant.FAIL);
				jsonObject.put(Constant.ERR_MESSAGE, "请输入当前地区");
				logger.error("请输入当前地区");
			}
		} catch (Exception e) {
			jsonObject.put(Constant.RESULT, Constant.FAIL);
			jsonObject.put(Constant.ERR_MESSAGE, "获取城市温度失败");
			logger.error("获取城市温度失败：", e.getMessage());
		}
		return new ResponseEntity<JSONObject>(jsonObject, null, HttpStatus.OK);
	}

}
